
package com.hlkj.pay.app.merchant.ext.impl.guogpay.ext;
/*
 * Hlpay-Plus aggregate payment system.
 * Copyright (c) 2024-2025 Hlpay Team Copyright has the right of final interpretation.
 */

import com.fasterxml.jackson.core.type.TypeReference;
import com.hlkj.framework.common.pojo.CommonResult;
import com.hlkj.framework.common.util.json.JsonUtils;
import com.hlkj.framework.extension.annotation.Extension;
import com.hlkj.pay.app.merchant.ext.dto.order.ChannelPayOrderContext;
import com.hlkj.pay.app.merchant.ext.dto.order.ChannelPayOrderQueryContext;
import com.hlkj.pay.app.merchant.ext.dto.order.ChannelRefundPayOrderContext;
import com.hlkj.pay.app.merchant.ext.impl.guogpay.GuogPayScenePayOrderExtPt;
import com.hlkj.pay.app.merchant.ext.impl.guogpay.constant.GuogPayConstant;
import com.hlkj.pay.app.merchant.ext.impl.guogpay.constant.GuogPayExtConstant;
import com.hlkj.pay.app.merchant.ext.impl.guogpay.dto.GuogPayConfig;
import com.hlkj.pay.app.merchant.ext.impl.guogpay.dto.req.OrderCreateReq;
import com.hlkj.pay.app.merchant.ext.impl.guogpay.dto.rsp.HttpResponse;
import com.hlkj.pay.app.merchant.ext.impl.guogpay.dto.rsp.OrdeCreateDataRsp;
import com.hlkj.pay.app.merchant.ext.impl.guogpay.utils.GuogPaySignUtil;
import com.hlkj.pay.app.merchant.ext.impl.guogpay.utils.HttpUtils;
import com.hlkj.pay.enums.PayEnums;
import com.hlkj.pay.infrastructure.model.order.PayOrderDO;
import com.hlkj.pay.infrastructure.model.pay.PayWayDO;
import com.hlkj.pay.infrastructure.model.pay.ProviderChannelConfigDO;
import com.hlkj.pay.util.MerchantUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import java.util.Objects;

/**
 * 主扫统一下单 用户扫支付码
 *
 * @author HlpayTeam
 * @date 2024/11/18 13:07
 */
@Slf4j
@Repository
@RequiredArgsConstructor
@Extension(bizId = GuogPayExtConstant.PAY)
public class GuogPayScanPayOrderExtPt extends GuogPaySceneCommonPayOrder implements GuogPayScenePayOrderExtPt {

    @Override
    public void submitChannelPayOrder(ChannelPayOrderContext channelPayOrderContext) {
//        ALIPAY	JSAPI，H5
//        WXPAY	JSAPI, MINI_PROGRAM, H5
        // 配置转换
        ProviderChannelConfigDO providerChannelConfigDO = channelPayOrderContext.getProviderChannelConfigDO();
        String channelConfig = providerChannelConfigDO.getParamsConfig();
        GuogPayConfig payConfig = getPayConfig(channelConfig, channelPayOrderContext.getMerchantAppChannelDO());
        PayOrderDO payOrderDO = channelPayOrderContext.getPayOrderDO();
        try {
            OrderCreateReq bodyReq = new OrderCreateReq();
            bodyReq.setMerchantNo(payConfig.getMerchantNo());
            bodyReq.setOutTradeNo(payOrderDO.getPayOrderNo());
            bodyReq.setRequestId(payOrderDO.getPayOrderNo());
            bodyReq.setTotalAmount(MerchantUtils.YuanToFen(payOrderDO.getAmount()));
            bodyReq.setSubject(payOrderDO.getSubject());
            bodyReq.setProductCode("QUICK_WAP_WAY");
            bodyReq.setReturnUrl(channelPayOrderContext.getRedirectUrl());
            bodyReq.setQuitUrl(channelPayOrderContext.getRedirectUrl());
            bodyReq.setCallbackUrl(channelPayOrderContext.getNotifyUrl());
//            bodyReq.setCallbackUrl("https://test-api.hbhlpay.com/applyments.ffpay/test");
            bodyReq.setTimestamp(getCurrenttime());

            String url = domain(channelPayOrderContext.isTest()) + GuogPayConstant.TRADE_CREATE;
            bodyReq.setSign(GuogPaySignUtil.sign(bodyReq, payConfig.getMd5Key()));
            log.info("国广支付下单req参数:{}", JsonUtils.toJsonString(bodyReq));
            String response = HttpUtils.post(url, JsonUtils.toJsonString(bodyReq));
            log.info("国广支付下单返回参数:{}", response);

            HttpResponse<OrdeCreateDataRsp> rspBody = JsonUtils.parseObject(response, new TypeReference<>() {
            });
            if ("0000".equals(rspBody.getCode())) {
                log.info("国广支付下单返回消息体:{}", rspBody);
                OrdeCreateDataRsp orderData = rspBody.getData();
                channelPayOrderContext.setPayDataType("form");
                channelPayOrderContext.setPayInfo(orderData.getPayData());
            } else {
                String respDesc = rspBody.getMessage();
                channelPayOrderContext.setProcessStatus(Boolean.FALSE);
                if (StringUtils.hasText(respDesc)) {
                    channelPayOrderContext.setRemark(respDesc);
                } else {
                    channelPayOrderContext.setRemark("国广支付下单查询返回错误信息为空,错误码为:" + rspBody.getCode());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("国广支付下单请求失败 message:{}", e.getMessage(), e);
            channelPayOrderContext.setRemark("国广支付下单请求失败,失败信息" + e.getMessage());
            channelPayOrderContext.setProcessStatus(Boolean.FALSE);
        }
    }

    private String getPayType(PayWayDO payWayDO) {
        PayEnums.PAY_TYPE payType = PayEnums.PAY_TYPE.fromByCode(payWayDO.getType());
        if (Objects.isNull(payType)) return "";
        switch (payType) {
            case WECHAT:
                return "WXPAY";
            case ALIPAY:
                return "ALIPAY";
        }
        return "";
    }

    private String getPaySubType(PayWayDO payWayDO) {
        PayEnums.SCENE_PAY_TYPE scenePayType = PayEnums.SCENE_PAY_TYPE.from(payWayDO.getSubType());
        PayEnums.PAY_TYPE payType = PayEnums.PAY_TYPE.fromByCode(payWayDO.getType());
        if (Objects.isNull(scenePayType) || Objects.isNull(payType)) return "";
        switch (scenePayType) {
            case APP:
            case H5:
                return "H5";
            case MINI_APP:
                return "MINI_PROGRAM";
            case JSAPI:
                return "JSAPI";
            case QR:
                switch (payType) {
                    case WECHAT:
                        return "JSAPI";
                    case ALIPAY:
                        return "NATIVE";
                }
        }
        return "";
    }

    @Override
    public void queryChannelPayOrder(ChannelPayOrderQueryContext channelPayOrderQueryContext) {
        commonQueryChannelPayOrder(channelPayOrderQueryContext);
    }

    @Override
    public void closeChannelPayOrder(ChannelPayOrderQueryContext channelPayOrderQueryContext) {
    }

    @Override
    public void queryChannelClosePayOrder(ChannelPayOrderQueryContext channelPayOrderQueryContext) {
    }

    @Override
    public void refundChannelPayOrder(ChannelRefundPayOrderContext channelRefundPayOrderContext) {
        commonRefundChannelPayOrder(channelRefundPayOrderContext);
    }

    @Override
    public void queryRefundChannelPayOrder(ChannelRefundPayOrderContext channelRefundPayOrderContext) {
        commonQueryRefundChannelPayOrder(channelRefundPayOrderContext);
    }

    @Override
    public boolean refundApply(ChannelRefundPayOrderContext channelRefundPayOrderContext) {
        return true;
    }

    @Override
    public CommonResult<String> channelOrderCode(ChannelPayOrderContext channelPayOrderContext) {
        return CommonResult.success();
    }

}
